package AddProduct;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class InsertIntoItems
 * This servlet insert data into ITEMS table in database
 * @author desso
 */
@WebServlet("/InsertIntoItems")
public class InsertIntoItems extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public InsertIntoItems() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession sess = request.getSession();
	    
	    try {
	    	Connection databaseConnection = SQL.getConnection();				
			insertIntoItems(request, sess, databaseConnection);
			response.sendRedirect("ChooseMaterialAndCategory");			
		} catch (SQLException | ClassNotFoundException e) {
			e.printStackTrace();
		}    
	}

	private void insertIntoItems(HttpServletRequest request, HttpSession sess, Connection dbConnection) throws SQLException {		
		PreparedStatement prepareStatement = dbConnection.prepareStatement(SQLStatements.INSERT_INTO_ITEMS_TABLE, new String[] { "id" });
		prepareStatement.setString(1, (String) sess.getAttribute("description"));
		prepareStatement.setInt(2, Integer.parseInt((String) sess.getAttribute("price")));
		prepareStatement.setInt(3, Integer.parseInt((String) sess.getAttribute("promotional price")));
		prepareStatement.setInt(4, Integer.parseInt((String) sess.getAttribute("whole sale price")));
		prepareStatement.setInt(5, 4);
		prepareStatement.setString(6, request.getParameter("producer"));
		prepareStatement.setString(7, request.getParameter("brand"));
		prepareStatement.executeUpdate();
		
		ResultSet rs = prepareStatement.getGeneratedKeys();
		if (rs != null && rs.next()) {
		    sess.setAttribute("item_id", rs.getLong(1));
		}
	}
}
